package com.yinhai.msg.email.tool;

import java.util.Map;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

//发送邮件
public class SendMailUtil {

    public static void SendMail(Map map) throws MessagingException {
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// 连接协议
        properties.put("mail.smtp.host", map.get("sendhost"));// 主机名  "smtp.qq.com"
        properties.put("mail.smtp.port", map.get("sendport"));// 端口号  465
        properties.put("mail.smtp.auth", "true");
        if ("1".equals(map.get("sendssl"))) {
            properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
        }
        if ("1".equals(map.get("sendtls"))) {
            properties.put("mail.smtp.starttls.enable", "true");// 设置是否使用tls安全连接
        }
        properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
        // 得到回话对象
        Session session = Session.getInstance(properties);
        // 获取邮件对象
        Message message = new MimeMessage(session);
        // 设置发件人邮箱地址
        message.setFrom(new InternetAddress((String) map.get("emailaddress")));
        String[] inbox = ((String) map.get("inbox")).split(",");
        InternetAddress[] address = new InternetAddress[inbox.length];
        for (int i = 0; i < inbox.length; i++) {
            address[i] = new InternetAddress(inbox[i]);
        }
        // 设置收件人邮箱地址
        message.setRecipients(Message.RecipientType.TO, address);
        //new InternetAddress[]{new InternetAddress((String) map.get("inbox")), new InternetAddress((String) map.get("inbox")), new InternetAddress((String) map.get("inbox"))}
        //message.setRecipient(Message.RecipientType.TO, new InternetAddress("xxx@qq.com"));//一个收件人
        // 设置邮件标题
        message.setSubject((String) map.get("sendtitle"));
        // 设置邮件内容
        message.setText((String) map.get("sendcontent"));
        // 得到邮差对象
        Transport transport = session.getTransport();
        // 连接自己的邮箱账户
        transport.connect((String) map.get("emailaddress"), (String) map.get("password"));// 密码为邮箱开通的stmp服务后得到的客户端授权码
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }
}
